const express = require('express')
const router = express.Router()
const File = require('../models/File')
const upload = require('../config/upload')
const { cleanOrphanFiles } = require('../utils/fileCleaner')
const authMiddleware = require('../middlewares/auth')

// 文件上传接口
router.post('/upload', authMiddleware(), upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '请选择要上传的文件' })
    }

    const newFile = new File({
      filename: req.file.filename,
      filePath: `/uploads/others/${req.file.filename}`,
      mimetype: req.file.mimetype,
      size: req.file.size
    })
    const savedFile = await newFile.save()
    res.status(201).json(savedFile)
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 手动清理孤立文件接口
router.delete('/cleanup', async (req, res) => {
  try {
    await cleanOrphanFiles()
    res.json({ message: '文件清理完成' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
